import { useEffect, useMemo, useState } from 'react';
import { history } from 'umi';
import { useDictionary } from './useDictionary';
import { NeedManageService } from '../services/ManageService';
import { SchemaManageAPI } from '@/components/SchemaComponent/SchemaManage/type';
import { getKeyRouter } from '@/utils';
import { isMomentSubmitFun, XQBZ_STATE, ZRBGH_STATE } from './Format';
import { getNeedManageTableColumns, getNeedManageTableHeaderActions, getNeedManageSearchColumns, NeedManageTab } from '../mconfig/index';
import { NeedUpdateService } from '../services/UpdateService';
import { Form, message } from 'antd';
import { BZZ_CHECKSTATE, SHZ_CHECKSTATE } from '../../Acommon';
import { NeedManageAPI } from './type';

/**
 * @useNeedManage 管理页hooks
 * @param curRes 权限信息
 * @returns
 */
export function useNeedManage({ curRes, locationProps }: NeedManageAPI.IManageType) {
  /**取消弹窗的显示和隐藏*/
  const [isShowManageCancel, setIsShowManageCancel] = useState<Record<string, any>>({
    isShow: false,
    resObj: null,
  });

  /** 表格选中行的key */
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  /** 表格选中行内容 */
  const [selectedRows, setSelectedRows] = useState<Record<string, any>[]>([]);

  /**撤销弹窗*/
  const [revokeState, setRevokeState] = useState<Record<string, any>>({});

  /**是否显示汇总弹窗*/
  const [isShowCollect, setIsShowCollect] = useState<Record<string, any>>({});

  // 作废表单实例
  const [cancelForm] = Form.useForm();

  // 存储当前的需求信息，用来数据显示以及对接接口参数
  const [needInfo, setNeedInfo] = useState<Record<string, any>>({});

  // API 接口
  const { findNeedService, cancelNeedService } = NeedUpdateService();

  const { findNeedRun } = findNeedService(); /**详情接口*/
  const { cancelNeedRun, cancelNeedLoading } = cancelNeedService(); /**作废接口*/

  /**详情接口调用*/
  const fetchFindNeed = async (params: Record<string, any>) => {
    const result = await findNeedRun(params);
    setNeedInfo(result?.obj);
  };

  /**作废需求 */
  const fetchCancelNeed = async (params: Record<string, any>) => {
    const { msgFlag, msg } = await cancelNeedRun(params);
    if (msgFlag) {
      setIsShowManageCancel({
        isShow: false,
        resObj: null,
      });
    }
    // return processResponse({ flag: msgFlag, message: msg, id: needInfo.id });
  };

  /**数据字典*/
  const { levelList, needStateList, checkStateList, supplyKindList, supplyWayList, cancelTypeList } = useDictionary();

  /**dataGird接口*/
  const {
    needManageRun,
    needManageDataSource,
    needManageLoading,
    needManageTableProps,
    reloadRequest,
    reloadRequests,
    manageTableParams,
  } = NeedManageService().getNeedManageService();

  /**头部权限切换*/
  const switchList: SchemaManageAPI.ISwitchList[] = useMemo(() => {
    // return NeedManageTab(curRes);
    return [];
  }, [curRes]);

  useEffect(() => {
    needManageRun(NeedManageTab(curRes));
  }, [curRes]);

  const onChangeManageCancelState = (state: Record<string, any>) => {
    // if (state?.isShow) {
    //   fetchFindNeed({ id: state?.resObj?.id });
    // }
    // cancelForm?.resetFields();
    setIsShowManageCancel(state);
  };

  /**取消的确定按钮*/
  const cancelSubmit = async () => {
    reloadRequest(manageTableParams);
  };
  /**
   * @operation
   * @description 管理页操作事件
   */
  const operation = {
    onOA: (resObj) => {
      history.push({
        pathname: `/purchaseNeedController/dealHomePage/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: resObj?.id,
          pageInfo: {
            id: resObj?.id,
          },
          pIDDetailInfo: {
            id: resObj?.id,
          },
        },
      });
    },
    onRevoke: (record) => {
      setRevokeState({
        isShow: true,
        resObj: record,
      });
    },
    onAdd: (value: number) => {
      history.push({
        pathname: `/purchaseNeedController/add/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          supplyWay: value,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onView: (record) => {
      if (record?.state == ZRBGH_STATE() && record?.checkState == BZZ_CHECKSTATE() && curRes?.['/purchaseNeedMaterialController/check']) {
        history.push({
          // 结果录入页面
          pathname: `/purchaseNeedMaterialController/check/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            info: record,
            returnPathName: locationProps?.pathname,
          },
        });
      } else if (record?.state == ZRBGH_STATE() && record?.checkState == SHZ_CHECKSTATE()) {
        history.push({
          // 新增编辑页
          pathname: `/purchaseNeedMaterialController/dataGrid/{params}/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            info: record,
            returnPathName: locationProps?.pathname,
            // delRouterName: history.location.pathname, //必传,要删除的路由名称
          },
        });
      } else {
        history.push({
          // 新增编辑页
          pathname: `/purchaseNeedController/getPurchaseNeedByID/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            info: record,
            isView: true,
            returnPathName: locationProps?.pathname,
          },
        });
      }

      // // 跳转OA页面
      // history.push({
      //   pathname: `/purchaseNeedController/dealHomePage/:${getKeyRouter()}${getKeyRouter()}`,
      //   state: {
      //     pageType: 'detail',
      //     id: record?.id,
      //     pageInfo: {
      //       id: record?.id,
      //     },
      //     pIDDetailInfo: {
      //       id: record?.id,
      //     },
      //   },
      // });
    },
    onEdit: (record: Record<string, any>) => {
      if (record?.state == ZRBGH_STATE() && record?.checkState == BZZ_CHECKSTATE() && curRes?.['/purchaseNeedMaterialController/check']) {
        history.push({
          // 结果录入
          pathname: `/purchaseNeedMaterialController/check/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            info: record,
            returnPathName: locationProps?.pathname,
          },
        });
      } else {
        history.push({
          // 新增编辑页
          pathname: `/purchaseNeedController/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            info: record,
            isView: false,
            returnPathName: locationProps?.pathname,
          },
        });
      }
    },
    onSync: (record: Record<string, any>) => {
      history.push({
        pathname: `/purchaseNeedMaterialController/check/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          info: record,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onCancel: (record: Record<string, any>) => {
      onChangeManageCancelState({ isShow: true, resObj: record });
    },
    onCollect: (record: Record<string, any>) => {
      if (selectedRowKeys?.length) {
        setIsShowCollect({ isShow: true, selectedRowKeys });
      } else {
        message?.warn('请选择需要汇总的月度计划');
      }
    },
    needDictionary: {
      needStateList,
      checkStateList,
      supplyWayList,
      curRes,
    },
  };

  const oversightMemo = useMemo(() => {
    if (!isMomentSubmitFun()) {
      return {};
    }
    let rowSelectInfo: Record<string, any> = {};
    rowSelectInfo = {
      rowSelection: {
        type: 'checkBox',
        getCheckboxProps: (record) => ({
          disabled: record?.state !== XQBZ_STATE(),
        }),
        selectedRowKeys,
        onSelect: (record: any, selected: boolean) => {
          if (selected) {
            // 添加
            if (record.state === XQBZ_STATE()) {
              setSelectedRowKeys([...selectedRowKeys, record.id]);
              setSelectedRows([...selectedRows, record]);
            }
          } else {
            // 去除
            const newSelectedRowKeys = selectedRowKeys.filter((key) => key !== record.id);
            const newSelectedRows = selectedRows.filter((row) => row.id !== record.id);
            setSelectedRowKeys(newSelectedRowKeys);
            setSelectedRows(newSelectedRows);
          }
        },
        onSelectAll: (selected: boolean, _, changeRows: any[]) => {
          let dataKeys: any[] = []; // 当前table渲染的数据key集合
          needManageDataSource?.forEach((item: Record<string, any>) => {
            if (item.state === XQBZ_STATE()) {
              dataKeys?.push(item?.id);
            }
          });
          if (selected) {
            //全选
            // 两个key合并去重
            let keylist = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
            setSelectedRowKeys(keylist);
            // 处理record
            setSelectedRows([...selectedRows, ...changeRows]);
          } else {
            //全不选
            // 处理key
            let newarr: any[] = selectedRowKeys?.filter((item) => {
              return !dataKeys?.includes(item);
            });
            setSelectedRowKeys(newarr);
            /**
             * 处理row 这里的changeRows代表被取消的rows集合
             * {keys} 拿的是被取消的rows集合的id集合
             * 再已经选择的数据中进行过滤
             * */
            let keys: any[] = [];
            changeRows?.forEach((item: any) => {
              keys?.push(item?.id);
            });
            const newRows = selectedRows?.filter((item) => {
              return keys?.indexOf(item?.id) == -1;
            });
            setSelectedRows(newRows);
          }

          // const dataKeys = needManageDataSource?.map((item) => item.id) || [];
          // let allKeys: any = [];
          // let allRows: any = [];
          // if (selected) {
          //   // 全选
          //   const validDataKeys = dataKeys.filter((key) => needManageDataSource.find((item) => item.id === key)?.state === XQBZ_STATE());
          //   // 如果初始没有选中行，使用全部有效数据键作为初始选中键
          //   const initialSelectedRowKeysForAll =
          //     selectedRowKeys.length === 0
          //       ? validDataKeys
          //       : selectedRowKeys.filter((key) => needManageDataSource.find((item) => item.id === key)?.state === XQBZ_STATE());
          //   allKeys = Array.from(new Set([...validDataKeys, ...initialSelectedRowKeysForAll]));
          //   const validChangeRows = changeRows.filter((row) => row.state === XQBZ_STATE());
          //   const initialSelectedRowsForAll = selectedRows.length === 0 ? validChangeRows : selectedRows.filter((row) => row.state === XQBZ_STATE());
          //   allRows = [...initialSelectedRowsForAll, ...validChangeRows];
          //   setSelectedRowKeys(allKeys);
          //   setSelectedRows(allRows);
          // } else {
          //   // 全不选
          //   const remainingKeys = selectedRowKeys.filter(
          //     (key) => needManageDataSource.find((item) => item.id === key)?.state === XQBZ_STATE() && !dataKeys.includes(key),
          //   );
          //   const remainingRows = selectedRows.filter((row) => row.state === XQBZ_STATE() && !changeRows.some((item) => item.id === row.id));
          //   setSelectedRowKeys(remainingKeys);
          //   setSelectedRows(remainingRows);
          // }
        },
      },
    };
    return rowSelectInfo;
  }, [selectedRowKeys, needManageDataSource]);

  // SchemaManage 组件表格属性
  const tableProps = {
    columns: getNeedManageTableColumns(operation),
    dataSource: needManageDataSource,
    // rowClassName: setTableRowClassName,
    loading: needManageLoading,
    pagination: needManageTableProps.pagination as any,
    rowKey: 'id',
    onPageChange: (current: number, pageSize: number) => {
      needManageRun({ ...manageTableParams, current, pageSize, ...NeedManageTab(curRes) });
    },
    ...oversightMemo,
  };

  // SchemaManage 组件顶部查询属性
  const searchProps = {
    switchList: switchList,
    onSwitch: (_: string | undefined | number, searchValues: any, params: any) => {
      needManageRun({ ...searchValues, ...params, ...NeedManageTab(curRes) });
    },
    searchList: getNeedManageSearchColumns({
      levelList,
      needStateList,
      checkStateList,
      supplyWayList,
      supplyKindList,
      cancelTypeList,
    }),
    onSearch: (params: any) => {
      needManageRun({ ...params, ...NeedManageTab(curRes) });
    },
    onReset: (params: any) => {
      needManageRun({ ...params, ...NeedManageTab(curRes) });
    },
  };

  // SchemaManage 组件表格头部操作按钮属性
  const actionList = getNeedManageTableHeaderActions(operation);

  return {
    operation,
    tableProps,
    searchProps,
    actionList,
    change: {
      onChangeManageCancelState,
      cancelSubmit,
      setRevokeState,
      reloadRequests,
      setIsShowManageCancel,
      setIsShowCollect,
    },
    state: {
      isShowManageCancel,
      needInfo,
      revokeState,
      isShowCollect,
    },
    MForm: {
      cancelForm,
    },
    servicesLoading: {
      cancelNeedLoading,
    },
  };
}
